package controller;
/*The LoginAction fro Login 
operation*/

import helper.UserType;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import databeans.Sid_Respondent;
import databeans.Survey;
import databeans.User;
import databeans.MailingList;
import formbeans.LoginForm;
import model.MailingListDAO;
import model.Model;
import model.Sid_RespondentDAO;
import model.UserDAO;
import model.SurveyDAO;
import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

public class LoginAction extends Action {
	private FormBeanFactory<LoginForm> formBeanFactory = FormBeanFactory.getInstance(LoginForm.class);
	private UserDAO userDAO;
	private SurveyDAO surveyDAO;
	private Sid_RespondentDAO sid_respondentDAO;
	private MailingListDAO mlDAO;
	
	//instantiation.
	public LoginAction(Model model) {
		userDAO = model.getUserDAO();
		surveyDAO = model.getSurveyDAO();
		sid_respondentDAO = model.getSid_RespondentDAO();
		mlDAO = model.getMailingListDAO();
	}
    //return Name.
	public String getName() {
		return "login.do";
	}
    
    public String perform(HttpServletRequest request) {
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        /*
         * After successful login, set the session.
         */
        HttpSession session = request.getSession(true);
        // check if it is directly from respondents' clicks;
        String res_id = request.getParameter("q");
        // for the tour page 
        String tour_id = request.getParameter("help");
        if(tour_id!=null){
        	if(tour_id.equals("tour")){
        		return "help.jsp";
        	}
        }
        
        if(res_id != null){
        	// identify if has hashpassword
        	String hash_password = request.getParameter("p");

        	if(hash_password==null||(hash_password.length()==0)) return "homepage.jsp";
        	//check if the hashpassword is same 
        	 try {
				User resp = userDAO.lookup(res_id);
				// find this respondents
				if (resp!=null) {
					String survey_id = request.getParameter("id");
					Survey survey = surveyDAO.lookup(new Integer(survey_id));
					Sid_Respondent sr = sid_respondentDAO.lookup(survey.getSid(), resp.getUserid());
					request.setAttribute("completed", sr.getCompleted());
				 	synchronized(session) {
			        	session.setAttribute("user",resp);
			        	session.setAttribute("resp_survey",survey);
			        }
					return "viewsurvey.jsp";
				}
				return "homepage.jsp";
			} catch (DAOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        try {
        	LoginForm form = formBeanFactory.create(request);
        	request.setAttribute("loginform",form);
        	
        	if (!form.isPresent()) {
        		return "homepage.jsp";
        	}
    		
    		//Do Validation,if there was something wrong, return to the homepage.
    		errors.addAll(form.checkLoginFormErrors());
    		if (errors.size() != 0) {
    			return "homepage.jsp";
    		}
    		
    		// Look up the user login in.
    		User user = userDAO.lookup(form.getUserid());   
    		if (user == null) {
    			errors.add("The user does not exist!");
    			return "homepage.jsp";
    		} else if (!user.checkPassword(form.getPassword())) {
    			errors.add("Incorrect password");
    			return "homepage.jsp";
			}
	        
	        synchronized(session) {
	        	session.setAttribute("user",user);
	        }
	        
	        if (user.getType() == UserType.ADMIN)
	        	return "admin.jsp";
	        // get the survey list of this researcher
	        if (user.getType() == UserType.RESEARCHER){
	        	Survey[] old_survey = surveyDAO.getUserSurveys(user.getUserid());
	        	MailingList[] old_mailingList = mlDAO.getMailingListByUserid(user.getUserid());
	        	synchronized(session) {
	        		session.setAttribute("survey_list", old_survey);
	        		session.setAttribute("email_list", old_mailingList);
	        	}
	        	return "researcher.jsp";
	        }
			return "respondent.jsp";
        } catch (DAOException e) {
        	errors.add(e.getMessage());
        	return "errors.jsp";
        } catch (FormBeanException e) {
        	errors.add(e.getMessage());
        	return "errors.jsp";
        }
    }
}
